package us.wili.dev.netty.service.impl;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import us.wili.dev.netty.model.GameResponseDto;
import us.wili.dev.netty.model.RequestCmd;
import us.wili.dev.netty.model.game.Player;
import us.wili.dev.netty.model.game.Room;
import us.wili.dev.netty.service.NettyEventService;
import us.wili.dev.netty.service.NettyMsgEventService;

import java.util.List;
import java.util.UUID;

@Service
public class NettyMsgEventServiceImpl implements NettyMsgEventService {

    @Autowired
    private NettyEventService eventService;

    @Override
    public void sendMessage(UUID session, String msg,Room room) {
        if (session!=null){
            GameResponseDto rsp = new GameResponseDto();
            rsp.setCmd(RequestCmd.DECLARE_ROOM_PLAYER_MSG.getCode());
            rsp.setData(msg);
            sendMsgToPlayerByRoom(room,rsp);
        }
    }

    @Override
    public void sendMsgToPlayerByRoom(Room room, GameResponseDto rsp) {
        sendMsgToIngamePlayerByRoom(room, rsp);
        sendMsgToWaitPlayerByRoom(room, rsp);
    }

    @Override
    public void sendMsgToIngamePlayerByRoom(Room room, GameResponseDto rsp) {
        sendMsgToList(room.getIngamePlayers(), rsp);
    }

    @Override
    public void sendMsgToWaitPlayerByRoom(Room room, GameResponseDto rsp) {
        sendMsgToList(room.getWaitPlayers(), rsp);
    }

    @Override
    public void sendMsgToList(List<Player> playerList, GameResponseDto rsp) {
        playerList.parallelStream().forEach(player -> sendMsgToPlayer(player, rsp));
        System.out.printf("toAllPlayers"+rsp.getData().toString());
    }

    @Override
    public void sendMsgToPlayer(Player player, GameResponseDto rsp) {
        if (player!=null&&player.getSession()!=null){
            eventService.sendText(player.getSession(),rsp);
        }
    }

    @Override
    public void sendNextTurnMessage(Integer nextTurn,Room room) {
        GameResponseDto rsp  =new GameResponseDto();
        rsp.setCmd(RequestCmd.GAME_PLAYER_TURN.getCode());
        rsp.setRequestId("onPlayerTurn");
        rsp.setData(nextTurn);
        sendMsgToPlayerByRoom(room,rsp);
        //轮到下一家操作 并开始计时

    }
}
